package com.qbw.app.module.vehicle.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.http.okhttp.HttpTask;
import com.lib.util.ResUtil;
import com.lib.util.ScreenUtil;
import com.lib.util.StringUtil;
import com.qbw.app.Constant;
import com.qbw.app.R;
import com.qbw.app.databinding.VehicleActivityWarningDetailBinding;
import com.qbw.app.manager.MapManager;
import com.qbw.app.model.TravelGps;
import com.qbw.app.model.Warning;
import com.qbw.app.module.common.activity.CommonActivity;
import com.qbw.app.module.common.util.Gps;
import com.qbw.app.module.common.util.HttpRequestUtil;
import com.qbw.app.module.common.util.PositionUtil;
import com.qbw.app.module.common.util.UniversalToastUtil;
import com.qbw.app.module.vehicle.VehicleDataBindingAdapter;
import com.qbw.app.module.vehicle.holder.VehicleMarderHolder;
import com.qbw.app.request.impl.VehicleRequest;
import com.qbw.l.L;
import com.qbw.log.XLog;
import com.qbw.spm.P;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static com.qbw.app.Constant.KEY_MAP;
import static com.qbw.app.Constant.MAP_BAIDU;
import static com.qbw.app.Constant.MAP_DEFAULT;
import static com.qbw.app.Constant.MAP_GOOGLE;
import static com.qbw.app.request.impl.VehicleRequest.METHOD_TRAVEL_GPS;

/**
 * @author QBW
 * @date 2019/8/27
 */
public class VehicleWarningDetailActivity extends CommonActivity<VehicleActivityWarningDetailBinding> implements OnMapReadyCallback {

    private GoogleMap mGoogleMap;
    private Warning mWarning;
    private float mBaiduInitScale = 15F;
    private float mGoogleInitScale = 15F;
    private Handler mHandler = new Handler();
    private InfoWindow mBaiduInfoWindow;
    private Marker mGoogleMarkerInfoWindow;

    public static void start(Context context, Warning warning) {
        Intent intent = new Intent(context, VehicleWarningDetailActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(Constant.KEY_WARNING, warning);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.vehicle_activity_warning_detail;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = savedInstanceState == null ? getIntent().getExtras() : savedInstanceState;
        mWarning = (Warning) args.getSerializable(Constant.KEY_WARNING);
        mBinding.setWarning(mWarning);
        mBinding.title.setSubTitleVisible(true);
        mBinding.title.setSubTitle(mWarning.getVehicleNickName());
        mBinding.executePendingBindings();
        mBinding.title.setListener(this);
        mBinding.ivAdd.setOnClickListener(this);
        mBinding.ivMinus.setOnClickListener(this);
        mBinding.vgBottom.setOnClickListener(this);
        mBinding.vgBottom.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return false;
            }
        });
        initMap();
    }

    private void initMap() {
        if (mGeneralManager.getMapManager().isUseBaidu()) {
            initBaidu();
        } else {
            initGoogle();
        }
    }

    private void initBaidu() {
        mBinding.bmapView.setVisibility(View.VISIBLE);
        mBinding.bmapView.showScaleControl(false);
        mBinding.bmapView.showZoomControls(false);

        BaiduMap map = mBinding.bmapView.getMap();
        map.setMyLocationEnabled(true);
        map.setMyLocationConfiguration(new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL,
                                                                   true,
                                                                   BitmapDescriptorFactory.fromResource(
                                                                           /*R.drawable
                                                                           .location_icon_route_end*/
                                                                           0)));
        //map.setOnMapClickListener(mBadiuMapClickListener);
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);
        map.setMapStatus(msu);

        //mLocationClient = new LocationClient(getApplicationContext());
        LocationClientOption option = new LocationClientOption();

        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；

        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认gcj02
        //gcj02：国测局坐标；
        //bd09ll：百度经纬度坐标；
        //bd09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回wgs84类型坐标

        option.setScanSpan(1000);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true

        option.setLocationNotify(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前WiFi是否超出有效期，若超出有效期，会先重新扫描WiFi，然后定位

        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        //mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明

        //mLocationClient.registerLocationListener(mBaiduLocationListener = new
        // ElecAreaAddActivity.MyBaiduLocationListener());

        //mLocationClient.start();
        //mLocationClient.requestLocation();
        afterInitMap();
        mBinding.bmapView.getMap().setOnMarkerClickListener(marker -> {
            Bundle bundle = marker.getExtraInfo();
            if (bundle != null) {
                if (mBaiduInfoWindow != null) {
                    mBinding.bmapView.getMap()
                            .hideInfoWindow();
                    mBaiduInfoWindow = null;
                    return true;
                }
                Serializable s = bundle.getSerializable(Constant.KEY_TAG);
                if (s instanceof Warning) {
                    Warning warning = (Warning) s;
                    VehicleMarderHolder marderHolder = new VehicleMarderHolder(this, null);
                    marderHolder.bindData(0,
                                          new VehicleMarderHolder.Data(warning.getAlarmName(),
                                                                       VehicleDataBindingAdapter.getVehicleTime(
                                                                               warning.getStartTime(), true)));
                    InfoWindow infoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(
                            marderHolder.itemView),
                                                           marker.getPosition(),
                                                           -ScreenUtil.dp2px(this, 50),
                                                           () -> {
                                                               mBinding.bmapView.getMap()
                                                                                .hideInfoWindow();
                                                               mBaiduInfoWindow = null;
                                                           });
                    mBaiduInfoWindow = infoWindow;
                    mBinding.bmapView.getMap().showInfoWindow(infoWindow);
                }
            }
            return true;
        });
       /* mBinding.bmapView.getMap().setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                mBaiduInfoWindow = null;
                mBinding.bmapView.getMap().hideInfoWindow();
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });*/
    }

    private void initGoogle() {
        mBinding.googleContainer.setVisibility(View.VISIBLE);
        com.google.android.gms.maps.SupportMapFragment mapFragment = (com.google.android.gms.maps.SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;
        mGoogleMap.getUiSettings().setCompassEnabled(false);
        CameraUpdate cameraUpdate = CameraUpdateFactory.zoomTo(15);
        mGoogleMap.moveCamera(cameraUpdate);
        afterInitMap();
        mGoogleMap.setInfoWindowAdapter(new GoogleInfoAdapter(this));
        mGoogleMap.setOnInfoWindowCloseListener(new GoogleMap.OnInfoWindowCloseListener() {
            @Override
            public void onInfoWindowClose(Marker marker) {
                // 点击地图时触发（没有办法可以屏蔽），当主动调用hideInfoWindow时不会触发此方法
                // 事件传递顺序OnInfoWindowClose-->OnMapClickListener
                // 不能在这里调用showInfoWindow，不起作用
            }
        });
        mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker.getTag() != null) {
                    // 一定要设置setOnMapClickListener始终显示，要不这里mGoogleMarkerInfoWindow一直为null
                    if (mGoogleMarkerInfoWindow != null) {
                        mGoogleMarkerInfoWindow.hideInfoWindow();
                        mGoogleMarkerInfoWindow = null;
                    } else {
                        mGoogleMarkerInfoWindow = marker;
                        marker.showInfoWindow();
                    }
                }
                // 要返回true，否则右下角会有简化图标
                return true;
            }
        });
        mGoogleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {
                if (mGoogleMarkerInfoWindow != null) {
                    mGoogleMarkerInfoWindow.hideInfoWindow();
                    mGoogleMarkerInfoWindow = null;
                }
            }
        });
        mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(com.google.android.gms.maps.model.LatLng latLng) {
                if (mGoogleMarkerInfoWindow != null) {
                    mGoogleMarkerInfoWindow.showInfoWindow();
                }
            }
        });
    }

    private static class GoogleInfoAdapter implements GoogleMap.InfoWindowAdapter {

        private Context mContext;

        public GoogleInfoAdapter(Context context) {
            mContext = context;
        }

        @Override
        public View getInfoWindow(Marker marker) {
            if (marker.getTag() instanceof Warning) {
                Warning warning = (Warning) marker.getTag();
                VehicleMarderHolder marderHolder = new VehicleMarderHolder(mContext, null);
                marderHolder.bindData(0,
                                      new VehicleMarderHolder.Data(warning.getAlarmName(),
                                                                   VehicleDataBindingAdapter.getVehicleTime(
                                                                           warning.getStartTime(), true)));
                return marderHolder.itemView;
            }
            return null;
        }

        @Override
        public View getInfoContents(Marker marker) {
            return null;
        }
    }

    private void afterInitMap() {
        long at = mWarning.getAlarmId();
        //显示位置点
        if (at == Constant.EVENT_DEVICE_OUT /*|| at == Constant.EVENT_POSSIBLE_CRASH*/) {
            if (mGeneralManager.getMapManager().isUseBaidu()) {
                baiduAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                         StringUtil.numberDouble(mWarning.getStartLongitude()),
                                         /*VehicleDataBindingAdapter.getAlarmIdImageFlag(mWarning.getAlarmId(),
                                                                                       R.drawable.vehicle_warning1)*/
                                         VehicleDataBindingAdapter.getAlarmIdImage(at,
                                                                                   R.drawable.vehicle_warning1));
            } else {
                googleAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                          StringUtil.numberDouble(mWarning.getStartLongitude()),
                                          /*VehicleDataBindingAdapter.getAlarmIdImageFlag(mWarning.getAlarmId(),
                                                                                        R.drawable.vehicle_warning1)*/
                                          VehicleDataBindingAdapter.getAlarmIdImage(at,
                                                                                    R.drawable.vehicle_warning1));
            }
        } else if (at == Constant.EVENT_POSSIBLE_CRASH) {
            if (mGeneralManager.getMapManager().isUseBaidu()) {
                baiduAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                        StringUtil.numberDouble(mWarning.getStartLongitude()),
                                         /*VehicleDataBindingAdapter.getAlarmIdImageFlag(mWarning.getAlarmId(),
                                                                                       R.drawable.vehicle_warning1)*/
                        R.drawable.possible_crash);
            } else {
                googleAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                        StringUtil.numberDouble(mWarning.getStartLongitude()),
                                          /*VehicleDataBindingAdapter.getAlarmIdImageFlag(mWarning.getAlarmId(),
                                                                                        R.drawable.vehicle_warning1)*/
                        R.drawable.possible_crash);
            }
        } else if (at == Constant.EVENT_SHOCK_AFTER_STALLING) {
            if (mGeneralManager.getMapManager().isUseBaidu()) {
                baiduAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                         StringUtil.numberDouble(mWarning.getStartLongitude()),
                                         /*VehicleDataBindingAdapter.getAlarmIdImageFlag(mWarning.getAlarmId(),
                                                                                       R.drawable.vehicle_warning1)*/
                                         R.drawable.shark_after_flameout);
            } else {
                googleAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                          StringUtil.numberDouble(mWarning.getStartLongitude()),
                                          /*VehicleDataBindingAdapter.getAlarmIdImageFlag(mWarning.getAlarmId(),
                                                                                        R.drawable.vehicle_warning1)*/
                                          R.drawable.shark_after_flameout);
            }
        } else if (at == Constant.EVENT_LOWER_ELE) {
            if (mGeneralManager.getMapManager().isUseBaidu()) {
                baiduAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                         StringUtil.numberDouble(mWarning.getStartLongitude()),
                                         /*VehicleDataBindingAdapter.getAlarmIdImageFlag(mWarning.getAlarmId(),
                                                                                       R.drawable.vehicle_warning1)*/
                                         R.drawable.lower_power);
            } else {
                googleAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                          StringUtil.numberDouble(mWarning.getStartLongitude()),
                                          /*VehicleDataBindingAdapter.getAlarmIdImageFlag(mWarning.getAlarmId(),
                                                                                        R.drawable.vehicle_warning1)*/
                                          R.drawable.lower_power);
            }
        } else if (at == Constant.EVENT_POSSIBLE_ROLLOVER) {
            if (mGeneralManager.getMapManager().isUseBaidu()) {
                baiduAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                         StringUtil.numberDouble(mWarning.getStartLongitude()),
                                        /* VehicleDataBindingAdapter.getAlarmIdImageFlag(mWarning.getAlarmId(),
                                                                                       R.drawable.vehicle_warning1),*/
                                         R.drawable.possible_rollover);
            } else {
                googleAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                          StringUtil.numberDouble(mWarning.getStartLongitude()),
                                          /*VehicleDataBindingAdapter.getAlarmIdImageFlag(mWarning.getAlarmId(),
                                                                                        R.drawable.vehicle_warning1),*/
                                          R.drawable.possible_rollover);
            }
        } else if (at == Constant.EVENT_ILLEGAL_MOVE) {
            if (mGeneralManager.getMapManager().isUseBaidu()) {
                baiduAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                         StringUtil.numberDouble(mWarning.getStartLongitude()),
                                         /*VehicleDataBindingAdapter.getAlarmIdImageFlag(mWarning.getAlarmId(),
                                                                                       R.drawable.vehicle_warning1)*/
                                         R.drawable.illegal_move);
            } else {
                googleAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                          StringUtil.numberDouble(mWarning.getStartLongitude()),
                                          /*VehicleDataBindingAdapter.getAlarmIdImageFlag(mWarning.getAlarmId(),
                                                                                        R.drawable.vehicle_warning1)*/
                                          R.drawable.illegal_move);
            }
        } else if (at == Constant.EVENT_INCREASE_SPEED) {
            if (mGeneralManager.getMapManager().isUseBaidu()) {
                baiduAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                         StringUtil.numberDouble(mWarning.getStartLongitude()),
                                         R.drawable.ji_add);
            } else {
                googleAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                          StringUtil.numberDouble(mWarning.getStartLongitude()),
                                          R.drawable.ji_add);
            }
        } else if (at == Constant.EVENT_REDUCE_SPEED) {
            if (mGeneralManager.getMapManager().isUseBaidu()) {
                baiduAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                         StringUtil.numberDouble(mWarning.getStartLongitude()),
                                         R.drawable.ji_minus);
            } else {
                googleAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                          StringUtil.numberDouble(mWarning.getStartLongitude()),
                                          R.drawable.ji_minus);
            }
        } else if (at == Constant.EVENT_TURN_HURRY) {
            if (mGeneralManager.getMapManager().isUseBaidu()) {
                baiduAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                         StringUtil.numberDouble(mWarning.getStartLongitude()),
                                         R.drawable.ji_turn);
            } else {
                googleAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                          StringUtil.numberDouble(mWarning.getStartLongitude()),
                                          R.drawable.ji_turn);
            }
        }
        if (at == Constant.EVENT_ELEC_AREA_IN || at == Constant.EVENT_ELEC_AREA_OUT) {
            if (mGeneralManager.getMapManager().isUseBaidu()) {
                baiduAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                         StringUtil.numberDouble(mWarning.getStartLongitude()),
                                         VehicleDataBindingAdapter.getAlarmIdImage(at,
                                                                                   R.drawable.vehicle_warning));
            } else {
                googleAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                          StringUtil.numberDouble(mWarning.getStartLongitude()),
                                          VehicleDataBindingAdapter.getAlarmIdImage(at,
                                                                                    R.drawable.vehicle_warning));
            }
        }


        //需要显示电子围栏
        if (at == Constant.EVENT_ELEC_AREA_IN || at == Constant.EVENT_ELEC_AREA_OUT) {
            showElectriaArea();
        }
        //需要显示轨迹
        if (at == Constant.EVENT_INCREASE_SPEED || at == Constant.EVENT_REDUCE_SPEED || at == Constant.EVENT_TURN_HURRY || at == Constant.EVENT_POSSIBLE_ROLLOVER || at == Constant.EVENT_POSSIBLE_CRASH || at == Constant.EVENT_ELEC_AREA_IN || at == Constant.EVENT_ELEC_AREA_OUT) {
            if (!TextUtils.isEmpty(mWarning.getTravelCode())) {
                mGeneralManager.getRequestManager()
                               .getVehicleRequest()
                               .getTravelGps(mWarning.getTravelCode(), "0", this)
                               .execute();
            }
        }
        //需要显示所有三级
        if (at == Constant.EVENT_ELEC_AREA_IN || at == Constant.EVENT_ELEC_AREA_OUT) {
            if (!TextUtils.isEmpty(mWarning.getTravelCode())) {
                mGeneralManager.getRequestManager()
                               .getVehicleRequest()
                               .getTravelAlarms(mWarning.getTravelCode(), this)
                               .execute();
            }
        }
        if (at == Constant.EVENT_POSSIBLE_ROLLOVER || at == Constant.EVENT_POSSIBLE_CRASH || at == Constant.EVENT_INCREASE_SPEED || at == Constant.EVENT_REDUCE_SPEED || at == Constant.EVENT_TURN_HURRY) {
            if (!TextUtils.isEmpty(mWarning.getTravelCode())) {
                mGeneralManager.getRequestManager()
                               .getVehicleRequest()
                               .getTravelAlarms(mWarning.getTravelCode(), this)
                               .execute();
            } else {
                if (mGeneralManager.getMapManager().isUseBaidu()) {
                    baiduAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                             StringUtil.numberDouble(mWarning.getStartLongitude()),
                                             VehicleDataBindingAdapter.getAlarmIdImage(at,
                                                                                       R.drawable.vehicle_warning));
                } else {
                    googleAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                              StringUtil.numberDouble(mWarning.getStartLongitude()),
                                              VehicleDataBindingAdapter.getAlarmIdImage(at,
                                                                                        R.drawable.vehicle_warning));
                }
                /*if (at == Constant.EVENT_INCREASE_SPEED) {
                    if (mGeneralManager.getMapManager().isUseBaidu()) {
                        baiduAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                                 StringUtil.numberDouble(mWarning.getStartLongitude()),
                                                 R.drawable.ji_add);
                    } else {
                        googleAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                                  StringUtil.numberDouble(mWarning.getStartLongitude()),
                                                  R.drawable.ji_add);
                    }
                } else if (at == Constant.EVENT_REDUCE_SPEED) {
                    if (mGeneralManager.getMapManager().isUseBaidu()) {
                        baiduAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                                 StringUtil.numberDouble(mWarning.getStartLongitude()),
                                                 R.drawable.ji_minus);
                    } else {
                        googleAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                                  StringUtil.numberDouble(mWarning.getStartLongitude()),
                                                  R.drawable.ji_minus);
                    }
                } else if (at == Constant.EVENT_TURN_HURRY) {
                    if (mGeneralManager.getMapManager().isUseBaidu()) {
                        baiduAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                                 StringUtil.numberDouble(mWarning.getStartLongitude()),
                                                 R.drawable.ji_turn);
                    } else {
                        googleAnimateAndAddMarker(StringUtil.numberDouble(mWarning.getStartLatitude()),
                                                  StringUtil.numberDouble(mWarning.getStartLongitude()),
                                                  R.drawable.ji_turn);
                    }
                }*/
            }
        }

    }

    private void baiduAnimateToPosition(double lat, double lon) {
        Gps gps = PositionUtil.gps84_to_bd09_byBaiduSdk(lat, lon);
        MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(new LatLng(gps.getWgLat(),
                                                                             gps.getWgLon()));
        // 移动到某经纬度
        mBinding.bmapView.getMap().animateMapStatus(update);
    }

    private void baiduAnimateAndAddMarker(double latitude,
                                          double longitude,
                                          int positionDrawableRes) {
        baiduAnimateAndAddMarker(latitude,
                                 longitude,
                                 positionDrawableRes,
                                 positionDrawableRes == R.drawable.travel_location || positionDrawableRes == R.drawable.travel_start || positionDrawableRes == R.drawable.travel_end ? null : mWarning);
    }

    /**
     * 移动到指定位置，并添加marker
     */
    private void baiduAnimateAndAddMarker(double latitude,
                                          double longitude,
                                          int positionDrawableRes,
                                          Serializable extra) {
        Gps gps = PositionUtil.gps84_to_bd09_byBaiduSdk(latitude, longitude);
        MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(new LatLng(gps.getWgLat(),
                                                                             gps.getWgLon()));
        // 移动到某经纬度
        mBinding.bmapView.getMap().animateMapStatus(update);

        int zindex = 5;
        Bundle bundle = null;
        if (extra != null) {
            bundle = new Bundle();
            bundle.putSerializable(Constant.KEY_TAG, extra);
            if (extra instanceof Warning) {
                Warning w = (Warning) extra;
                if (w.getAlarmId() == mWarning.getAlarmId() && w.getStartTime() == mWarning.getStartTime()) {
                    L.GL.d("current alarm[%s]", mWarning.getAlarmName());
                    zindex = 6;
                }
            }
        }
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), positionDrawableRes);
        if (zindex == 6) {
            bitmap = currentWarningBitmap(bitmap);
        }
        //添加marker
        Overlay overlay = mBinding.bmapView.getMap()
                                           .addOverlay(new com.baidu.mapapi.map.MarkerOptions().position(
                                                   new LatLng(gps.getWgLat(), gps.getWgLon()))
                                                                                               .icon(BitmapDescriptorFactory
                                                                                                             .fromBitmap(
                                                                                                                     bitmap)));
        if (bundle != null) {
            overlay.setExtraInfo(bundle);
        }
        overlay.setZIndex(zindex);
    }

    private View createMarkerView(int res, boolean bigger) {
        View view = LayoutInflater.from(this)
                                  .inflate(bigger ? R.layout.vehicle_view_current_warning : R.layout.vehicle_view_warning,
                                           null);
        ImageView ivv = view.findViewById(R.id.iv);
        ivv.setImageResource(res);
        return view;
    }

    private void googleAnimateToPosition(double lat, double lon) {
        if (mGoogleMap == null) {
            XLog.e("mGoogleMap == null");
            return;
        }
        Gps gps = PositionUtil.gps84_To_Gcj02(lat, lon);
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(new com.google.android.gms.maps.model.LatLng(
                gps.getWgLat(),
                gps.getWgLon()));
        mGoogleMap.moveCamera(cameraUpdate);
    }

    private void googleAnimateAndAddMarker(double latitude,
                                           double longitude,
                                           int positionDrawableRes) {
        googleAnimateAndAddMarker(latitude,
                                  longitude,
                                  positionDrawableRes,
                                  positionDrawableRes == R.drawable.travel_location || positionDrawableRes == R.drawable.travel_start || positionDrawableRes == R.drawable.travel_end ? null : mWarning);

    }

    private void googleAnimateAndAddMarker(double latitude,
                                           double longitude,
                                           int positionDrawableRes,
                                           Serializable extra) {
        Gps _gps = PositionUtil.gps84_To_Gcj02(latitude, longitude);
        // 移动到某经纬度
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new com.google.android.gms.maps.model.LatLng(
                _gps.getWgLat(),
                _gps.getWgLon()), 11);
        mGoogleMap.moveCamera(cameraUpdate);


        int zindex = 5;
        if (extra instanceof Warning) {
            Warning ew = (Warning) extra;
            if (ew.getAlarmId() == mWarning.getAlarmId() && ew.getStartTime() == mWarning.getStartTime()) {
                zindex = 6;
            }
        }
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), positionDrawableRes);
        if (zindex == 6) {
            bitmap = currentWarningBitmap(bitmap);
        }
        //添加marker
        Marker marker = mGoogleMap.addMarker(new MarkerOptions().icon(com.google.android.gms.maps.model.BitmapDescriptorFactory
                                                                              .fromBitmap(bitmap))
                                                                .position(new com.google.android.gms.maps.model.LatLng(
                                                                        _gps.getWgLat(),
                                                                        _gps.getWgLon())));
        if (extra != null) {
            //Bundle bundle = new Bundle();
            //bundle.putSerializable(Constant.KEY_TAG, extra);
            //marker.set(bundle);
            marker.setTag(extra);
        }
        marker.setZIndex(zindex);
    }

    private static Bitmap currentWarningBitmap(Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postScale(1.5f, 1.5f);
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap,
                                               0,
                                               0,
                                               bitmap.getWidth(),
                                               bitmap.getHeight(),
                                               matrix,
                                               true);
        bitmap.recycle();
        return resizeBmp;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(Constant.KEY_WARNING, mWarning);
    }

    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        super.onHttpSuccess(httpTask, entity);
        String method = httpTask.getMethod();
        if (method.equals(METHOD_TRAVEL_GPS)) {
            TravelGps.Response response = (TravelGps.Response) entity;
            showTravel(response);
        } else if (method.equals(VehicleRequest.METHOD_TRAVEL_ALRAMS)) {
            Warning.ResponseList res = (Warning.ResponseList) entity;
            updateAlarm(res);
        }
    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        super.onHttpFailed(httpTask, errorCode, message);
        message = HttpRequestUtil.getMessage(errorCode, message);
        UniversalToastUtil.showToast(message);
    }

    public void updateAlarm(Warning.ResponseList alarmResponse) {
        int size;
        if ((size = alarmResponse.size()) > 0) {
            double lat;
            double lng;
            int did;
            boolean animateToPosition = true;

            Warning warning;
            for (int i = size - 1; i >= 0; i--) {
                warning = alarmResponse.getData().get(i);
                lat = StringUtil.numberDouble(warning.getStartLatitude());
                lng = StringUtil.numberDouble(warning.getStartLongitude());
                if ((int) lat == 0 && (int) lng == 0) {
                    continue;
                }
                did = VehicleDataBindingAdapter.getAlarmIdImage(warning.getAlarmId(),
                                                                R.drawable.vehicle_warning1);
                if (did == 0) {
                    continue;
                }
                if (MapManager.getInstance().isUseBaidu()) {
                    Gps gps = new Gps(lat, lng);
                    baiduAnimateAndAddMarker(gps.getWgLat(), gps.getWgLon(), did, warning);
                } else {
                    Gps gps = new Gps(lat, lng);
                    googleAnimateAndAddMarker(gps.getWgLat(), gps.getWgLon(), did, warning);
                }
            }
        }
    }

    private int getJiDrawable(long alarmId) {
        int d = 0;
        if (alarmId == Constant.EVENT_INCREASE_SPEED) {
            d = R.drawable.ji_add;
        } else if (alarmId == Constant.EVENT_REDUCE_SPEED) {
            d = R.drawable.ji_minus;
        } else if (alarmId == Constant.EVENT_TURN_HURRY) {
            d = R.drawable.ji_turn;
        }
        return d;
    }

    private void showTravel(TravelGps.Response response) {
        List<TravelGps> travelGpss = response.getData();
        int gpsSize = response.size();
        L.GL.d("gpsSize[%d]", gpsSize);
        if (gpsSize <= 0) {
            L.GL.w("no gps data");
            return;
        }
        if (mGeneralManager.getMapManager().isUseBaidu()) {
            //mBinding.bmapView.getMap().clear();
            if (gpsSize == 1) {
                TravelGps gps = travelGpss.get(0);
                L.GL.w("on gps[%f, %f]", gps.getLatitude(), gps.getLongitude());
                baiduAnimateAndAddMarker(gps.getLatitude(),
                                         gps.getLongitude(),
                                         R.drawable.travel_location);
            } else {
                //if (!mUpdateByManual) {
                TravelGps centerGps = travelGpss.get(gpsSize / 2);
                baiduAnimateToPosition(centerGps.getLatitude(), centerGps.getLongitude());
                //}

                TravelGps startGps = travelGpss.get(gpsSize - 1);
                mBinding.bmapView.getMap()
                                 .addOverlay(new com.baidu.mapapi.map.MarkerOptions().icon(
                                         BitmapDescriptorFactory.fromResource(R.drawable.travel_start))
                                                                                     .position(new LatLng(
                                                                                             startGps.getLatitude(),
                                                                                             startGps.getLongitude())))
                                 .setZIndex(4);
                TravelGps endGps = travelGpss.get(0);
                mBinding.bmapView.getMap()
                                 .addOverlay(new com.baidu.mapapi.map.MarkerOptions().icon(
                                         BitmapDescriptorFactory.fromResource(R.drawable.travel_end))
                                                                                     .position(new LatLng(
                                                                                             endGps.getLatitude(),
                                                                                             endGps.getLongitude())))
                                 .setZIndex(3);


                TravelGps travelGps;
                com.baidu.mapapi.model.LatLngBounds.Builder builder = new com.baidu.mapapi.model.LatLngBounds.Builder();
                List<LatLng> latLngs = new ArrayList<>();
                //int seekProgress = gpsSize - mTravelProgress;
                for (int i = gpsSize - 1; i >= 0; i--) {
                    travelGps = travelGpss.get(i);
                    //经纬度都是0的舍弃
                    if (travelGps.getLatitude() == 0f && travelGps.getLongitude() == 0f) {
                        continue;
                    }
                    //if (i >= seekProgress) {
                    latLngs.add(new LatLng(travelGps.getLatitude(), travelGps.getLongitude()));
                    //}
                    builder.include(new LatLng(travelGps.getLatitude(), travelGps.getLongitude()));
                }

                L.GL.e("here1，latLngs[%d],gpsSize[%d]", latLngs.size(), gpsSize);
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        L.GL.e("her3");
                        //if (!mUpdateByManual) {
                        mBinding.bmapView.getMap()
                                         .animateMapStatus(MapStatusUpdateFactory.newLatLngBounds(
                                                 builder.build(),
                                                 mBinding.bmapView.getWidth() - ScreenUtil.dp2px(
                                                         VehicleWarningDetailActivity.this,
                                                         100),
                                                 mBinding.bmapView.getHeight() - ScreenUtil.dp2px(
                                                         VehicleWarningDetailActivity.this,
                                                         350)));
                        //}
                        L.GL.d("latLngs[%d]", latLngs.size());
                        if (latLngs.size() >= 2) {
                            OverlayOptions ooPolyline = new PolylineOptions().width(Constant.TRAVEL_LINE_WIDTH)
                                                                             .color(ResUtil.getColor(
                                                                                     R.color.travel_line_color))
                                                                             .points(latLngs);
                            mBinding.bmapView.getMap().addOverlay(ooPolyline);
                        }
                    }
                }, 500);
            }
        } else {
            if (mGoogleMap == null) {
                //mNeedShowTravel = true;
                return;
            }
            //mGoogleMap.clear();
            if (gpsSize == 1) {
                TravelGps gps = travelGpss.get(0);
                googleAnimateAndAddMarker(gps.getLatitude(),
                                          gps.getLongitude(),
                                          R.drawable.travel_location);
            } else {
                TravelGps startGps = travelGpss.get(gpsSize - 1);
                TravelGps endGps = travelGpss.get(0);
                mGoogleMap.addMarker(new com.google.android.gms.maps.model.MarkerOptions().icon(com.google.android.gms.maps.model.BitmapDescriptorFactory
                                                                                                        .fromResource(
                                                                                                                R.drawable.travel_start))
                                                                                          .position(
                                                                                                  new com.google.android.gms.maps.model.LatLng(
                                                                                                          startGps.getLatitude(),
                                                                                                          startGps.getLongitude())))
                          .setZIndex(4);
                mGoogleMap.addMarker(new com.google.android.gms.maps.model.MarkerOptions().icon(com.google.android.gms.maps.model.BitmapDescriptorFactory
                                                                                                        .fromResource(
                                                                                                                R.drawable.travel_end))
                                                                                          .position(
                                                                                                  new com.google.android.gms.maps.model.LatLng(
                                                                                                          endGps.getLatitude(),
                                                                                                          endGps.getLongitude())))
                          .setZIndex(3);

                TravelGps travelGps;
                com.google.android.gms.maps.model.PolylineOptions polylineOptions = new com.google.android.gms.maps.model.PolylineOptions();
                for (int i = gpsSize - 1; i >= 0; i--) {
                    travelGps = travelGpss.get(i);
                    //经纬度都是0的舍弃
                    if (travelGps.getLatitude() == 0f && travelGps.getLongitude() == 0f) {
                        continue;
                    }
                    polylineOptions.add(new com.google.android.gms.maps.model.LatLng(travelGps.getLatitude(),
                                                                                     travelGps.getLongitude()));
                }
                polylineOptions.width(Constant.TRAVEL_LINE_WIDTH)
                               .color(ResUtil.getColor(R.color.travel_line_color));
                mGoogleMap.addPolyline(polylineOptions);

                LatLngBounds.Builder builder = new LatLngBounds.Builder();
                builder.include(new com.google.android.gms.maps.model.LatLng(startGps.getLatitude(),
                                                                             startGps.getLongitude()));
                builder.include(new com.google.android.gms.maps.model.LatLng(endGps.getLatitude(),
                                                                             endGps.getLongitude()));
                CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(builder.build(), 100);
                mGoogleMap.moveCamera(cu);
            }
        }
    }

    private void showElectriaArea() {
        if (mWarning == null) {
            return;
        }
        if (mGeneralManager.getMapManager().isUseBaidu()) {
            Warning.ElectricArea.InfoList areas = mWarning.getFenceJsonModel();
            if (areas != null && !areas.isEmpty()) {
                for (Warning.ElectricArea e : areas.getList()) {
                    baiduAddOverlay(e.getLatitude(), e.getLongitude(), (int) e.getRadius());
                }
            }
        } else {
            Warning.ElectricArea.InfoList areas = mWarning.getFenceJsonModel();
            if (areas != null && !areas.isEmpty()) {
                for (Warning.ElectricArea e : areas.getList()) {
                    googleAddOverlay(e.getLatitude(), e.getLongitude(), (int) e.getRadius());
                }
            }
        }
    }

    /**
     * 电子围栏
     * 传入的参数坐标系为gps84
     */
    private void baiduAddOverlay(double latitude, double longitude, int radius) {
        //mBinding.bmapView.getMap().clear();
        Gps _gps = PositionUtil.gps84_to_bd09_byBaiduSdk(latitude, longitude);
        LatLng llCircle = new LatLng(_gps.getWgLat(), _gps.getWgLon());
        OverlayOptions ooCircle = new CircleOptions().fillColor(0x3343d1a3)
                                                     .center(llCircle)
                                                     .stroke(new Stroke(5, 0x3343d1a3))
                                                     .radius(radius);
        mBinding.bmapView.getMap().addOverlay(ooCircle);
        baiduAnimateToPosition(latitude, longitude);
    }

    /**
     * 电子围栏
     * 传入的参数坐标系为gps84
     */
    private void googleAddOverlay(double latitude, double longitude, int radius) {
        Gps _gps = PositionUtil.gps84_To_Gcj02(latitude, longitude);
        mGoogleMap.addCircle(new com.google.android.gms.maps.model.CircleOptions().center(new com.google.android.gms.maps.model.LatLng(
                _gps.getWgLat(),
                _gps.getWgLon()))
                                                                                  .radius(radius)
                                                                                  .strokeWidth(5)
                                                                                  .strokeColor(Color.parseColor(
                                                                                          "#3343d1a3"))
                                                                                  .fillColor(Color.parseColor(
                                                                                          "#3343d1a3")));
        googleAnimateToPosition(latitude, longitude);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int vid = v.getId();
        if (vid == R.id.iv_add) {
            scaleMap(true);
        } else if (vid == R.id.iv_minus) {
            scaleMap(false);
        }
    }

    private void scaleMap(boolean bigger) {
        String map = P.getString(KEY_MAP, MAP_DEFAULT);
        switch (map) {
            case MAP_BAIDU:
                mBaiduInitScale += (bigger ? .5F : -.5F);
                MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(mBaiduInitScale);
                mBinding.bmapView.getMap().setMapStatus(msu);
                break;
            case MAP_GOOGLE:
                mGoogleInitScale += (bigger ? .5F : -.5F);
                if (mGoogleMap != null) {
                    CameraUpdate cameraUpdate = CameraUpdateFactory.zoomTo(mGoogleInitScale);
                    mGoogleMap.moveCamera(cameraUpdate);
                }
                break;
            default:
                break;
        }
    }
}
